<?php

function get_hostip_by_name($domain, $realtime = false, $timecache = 300000) {
    global $IS_TEST;

    $arr = explode('.', $domain);
    $length = count($arr);
    $extk = $length - 1;
    $dok = $length - 2;
    $maindomain = $arr[$dok] . '.' . $arr[$extk];
    $subdomain = $domain;
    if ($length == 2) {
        $subdomain = 'www.' . $maindomain;
    }

    $HostIpCacheFile = APP_ROOT_DIR . '/data/hostip-cache/host-ip/' . substr(md5($maindomain), 0, 2) . '/' . $subdomain . '.txt';
    if ($IS_TEST) {
        if (file_exists($HostIpCacheFile)) {
            $json = file_get_contents($HostIpCacheFile);
            log::n('cache gethostbyname[' . $subdomain . ']=>ip[' . $json . ']');
            return $json;
        } else {
            return false;
        }
    }
    if (!$realtime && (file_exists($HostIpCacheFile) && time() - filemtime($HostIpCacheFile) < $timecache)) {
        $json = file_get_contents($HostIpCacheFile);
        log::n('cache gethostbyname[' . $subdomain . ']=>ip[' . $json . ']');
        return $json;
    }

    $ip = gethostbyname($subdomain);
    log::n('realtime gethostbyname[' . $subdomain . ']=>ip[' . $ip . ']');

    foreach (explode('.', $ip) as $i) {
        if (!is_numeric($i)) {
            log::w('get host-ip format error[' . $ip . '],domain[' . $domain . ']');
            return false;
        }
    }
    FCheckDir($HostIpCacheFile);
    file_put_contents($HostIpCacheFile, $ip);

    return $ip;
}

?>